<?php
/**
 * The Validator class
 *
 */
class Validator
{
	/**
	 * Constructor placeholder
	 * Prevent the Validator class from instantiating
	 * Singleton Pattern
	 */
	private function __construct()
	{
	}

	static private function _ban($value, $ruleValue)
	{
		return !preg_match($ruleValue, $value);
	}

	static private function _mask($value, $ruleValue)
	{
		return preg_match($ruleValue, $value);
	}

	static private function _max_length($value, $ruleValue)
	{
		return mb_strlen($value) <= $ruleValue;
	}

	static private function _min_length($value, $ruleValue)
	{
		return mb_strlen($value) >= $ruleValue;
	}

	static private function _max_value($value, $ruleValue)
	{
		return $value <= $ruleValue;
	}

	static private function _min_value($value, $ruleValue)
	{
		return $value >= $ruleValue;
	}

	static private function _required($value, $ruleValue)
	{
		return 0 < strlen($value);
	}

	/**
	 * Validate an element
	 * 
	 * @param array $element 
	 * @return array 
	 */
	static private function _validateElement($element)
	{
		$errorTotal = 0;
		$errorMessages = array();
		$label = $element['dtd']['label'];
		$value = $element['value'];

		$ruleTotal = count($element['dtd']['rules']);
		if (is_array($element['dtd']['rules']) && $ruleTotal > 0)
		{
			$rules = $element['dtd']['rules'];
			$rules['required'] = isset($rules['required']) ? $rules['required'] : false;
			$explain = isset($element['dtd']['explain']) ? $element['dtd']['explain'] : array();

			if (false == $rules['required'] && (is_null($value) || 0 == strlen($value)))
			{
			}
			else
			{
				foreach ($rules as $key => $val)
				{
					$validateFunction = '_' . $key;
					if (!self::$validateFunction($value, $rules[$key]))
					{
						$errorTotal ++;
						$errorMessages[$key] = $label . (isset($explain[$key]) ? $explain[$key] : Config::$array['validator']['error_explain'][$key]);
					}
				}
			}
		}
		return array('error_total' => $errorTotal, 'error_messages' => $errorMessages);
	}

	/**
	 * Validate the data from client
	 * 
	 * @param array $args 
	 * @return array 
	 */
	static public function validate($validateCondition, &$validatedInput)
	{
		$errorTotal = 0;
		$errorMessages = array();
		foreach ($validateCondition as $key => $element)
		{
			$result = self::_validateElement($element);
			if ($result['error_total'])
			{
				$errorTotal ++;
				$errorMessages[$key] = $result['error_messages'];
			}
			else
			{
				$validatedInput[$key] = $element['value'];
			}
		}
		return array('error_total' => $errorTotal, 'error_messages' => $errorMessages);
	}
}
